package org.demo.es.config;

import co.elastic.clients.elasticsearch.ElasticsearchClient;
import co.elastic.clients.json.jackson.JacksonJsonpMapper;
import co.elastic.clients.transport.ElasticsearchTransport;
import co.elastic.clients.transport.rest_client.RestClientTransport;
import org.apache.http.HttpHost;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.elasticsearch.client.RestClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.StringUtils;

/**
 * Elasticsearch配置类
 * @author moxiaoli
 */
@Configuration
public class ElasticsearchConfig {

    @Value("${elasticsearch.endpoint}")
    public String endpoint;

    @Value("${elasticsearch.username}")
    public String username;

    @Value("${elasticsearch.password}")
    public String password;

    @Bean
    public ElasticsearchClient elasticsearchClient(){
        if (!StringUtils.hasText(endpoint)) {
            throw new RuntimeException("elasticsearch endpoint是必须的");
        }
        // 创建鉴权所需的CredentialsProvider
        final BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider();
        // 这里替换为你的用户名和密码
        credentialsProvider.setCredentials(AuthScope.ANY,
                new UsernamePasswordCredentials(username, password));
        RestClient restClient = RestClient
                .builder(HttpHost.create(endpoint))
                .setHttpClientConfigCallback(httpClientBuilder ->
                        httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider)
                )
                .build();
        ElasticsearchTransport transport = new RestClientTransport(
                restClient, new JacksonJsonpMapper());
        return new ElasticsearchClient(transport);
    }
}
